from ctypes import *

import encoder
import win32con


BUFSIZE = 4096

INVALID_HANDLE_VALUE = -1
ERROR_PIPE_CONNECTED = 535

pipeName = "\\\\.\\pipe\\mynamedpipe"

def generatePipe(path, media, stream, res, codec):
    hPipe = windll.kernel32.CreateNamedPipeA(pipeName,
                                             win32con.PIPE_ACCESS_DUPLEX,
                                             win32con.PIPE_TYPE_MESSAGE |
                                             win32con.PIPE_READMODE_MESSAGE|
                                             win32con.PIPE_WAIT,
                                             win32con.PIPE_UNLIMITED_INSTANCES,
                                             BUFSIZE, BUFSIZE,
                                             0,
                                             None)

    if(hPipe == INVALID_HANDLE_VALUE):
        print "Error in creating Named Pipe"
        return 0

    encoder.encoder("\"" + path + "\"", "\"" + pipeName + "\"", media, stream, res, codec)

    waitConnection(hPipe)
    return hPipe


def waitConnection(hPipe):
    fConnected = windll.kernel32.ConnectNamedPipe(hPipe, None)

    if ((fConnected == 0) and (windll.kernel32.GetLastError() == ERROR_PIPE_CONNECTED)):
        fConnected = 1

    if (not fConnected):
        print "Erro na conexao do encoder com o pipe"
        windll.kernel32.CloseHandle(hPipe)




if __name__ == "__main__":
    generatePipe("entrada.mpg", 1, 1)